
package com.gzbsoft.sc.modules.sys.service.impl;
import cn.hutool.core.map.MapUtil;
import com.gzbsoft.sc.common.utils.R;
import com.gzbsoft.sc.modules.sys.dao.SysUserTokenDao;
import com.gzbsoft.sc.modules.sys.entity.SysUser;
import com.gzbsoft.sc.modules.sys.entity.SysUserToken;
import com.gzbsoft.sc.modules.sys.oauth2.TokenGenerator;
import com.gzbsoft.sc.modules.sys.service.SysUserTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
@Service
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserToken, Long> implements SysUserTokenService {
    private final SysUserTokenDao sysUserTokenDao;
    private final static int EXPIRE = 3600 * 12;
    public SysUserTokenServiceImpl(SysUserTokenDao sysUserTokenDao) {
        this.sysUserTokenDao = sysUserTokenDao;
    }
    @Override
    public R createToken(Long userId) {
        String token = TokenGenerator.generateValue();
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        SysUserToken tokenEntity = sysUserTokenDao.findByProperty("user.id", userId).orElse(null);
        if (tokenEntity == null) {
            tokenEntity = new SysUserToken();
            tokenEntity.setUser(new SysUser(userId));
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(expireTime);
            sysUserTokenDao.save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(expireTime);
            sysUserTokenDao.update(tokenEntity);
        }
        HashMap<String, Object> map = MapUtil.of("token", token);
        map.put("expire", EXPIRE);
        return R.ok().setObj(map);
    }
    @Override
    public void logout(Long userId) {
        String token = TokenGenerator.generateValue();
        SysUserToken tokenEntity = new SysUserToken();
        tokenEntity.setUser(new SysUser(userId));
        tokenEntity.setToken(token);
        sysUserTokenDao.update(tokenEntity);
    }
}
